import router from "./router";
import { ElMessage } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, setToken, getUserId, setUserId } from "@/utils/auth";
import { getloginToken } from "@/api/login";
import { isRelogin } from "@/utils/request";
// 获取全局状态
import useUserStore from "@/store/modules/user";
import routerListStore from "@/store/modules/routerList";
// 引入接口
import { addRouterLogApi } from "@/api/logs";

// 进度条
NProgress.configure({ showSpinner: false });

// 需要登录的路由名单
const loginList = [];
// 不需要统计的路由名单
const noStatisticsList = [
  '/',
  '/redirect',
  '/index',
  '/home',
  '/home/index',
  '/login',
  '/register',
  '/forgotPassword',
  '/informationRetrieval/historicalSeismicInformation', //历史地震信息
];
// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  if (to.name && to.name != 'index') {
    let routerList = router.options.routes[router.options.routes.length - 1].children.slice(1);
    let newList = {};
    let newName = to.meta.title;
    let newPath = to.path;
    routerList.forEach(item => {
      if (to.path.includes(item.path)) {
        newList = item
      }
    })
    routerListStore().getNewRouter(newList, newName, newPath)
  }
  // 通过Ticket获取token
  if (to.query.cssSsoTicket) {
    const cssSsoTicket = to.query.cssSsoTicket;
    await getloginToken(cssSsoTicket).then((res) => {
      if (res.code == 200) {
        setToken(res.token);
        setUserId(res.userId);
      }
    });
  }
  // 判断token
  if (getToken()) {
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true;
        // 判断当前用户是否已拉取完user_info信息
        await useUserStore()
          .getInfo(getUserId())
          .then(async () => {
            isRelogin.show = false;
            next();
          })
          .catch((err) => {
            useUserStore()
              .logOut()
              .then((res) => {
                ElMessage.error(err);
                if (res.retUrl) {
                  location.href = res.retUrl;
                } else {
                  next('/login')
                }
              });
          });
      } else {
        next();
      }
    }
  }
  // 没有token
  else {
    // 需要登录的路由跳转登录页
    if (loginList.indexOf(to.path) !== -1) {
      location.href = import.meta.env.VITE_APP_API_SERVE + import.meta.env.VITE_APP_BASE_API;
      // next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
    // 默认放行
    else {
      next()
    }
  }
})

// 路由后置守卫
router.afterEach((to, from) => {
  NProgress.done();
  // 添加路由访问日志
  addRouterLogs(to);
});

/*
  添加路由访问日志
  params: {
    to: '当前路由'，
    options: '默认参数'
  }
*/
export function addRouterLogs(to, options = { opType: '浏览', moduleName: '', path: '', dataType: '', sign: '0' }) {
  if (to) {
    const arrPath = to.path.match(/^\/\S+?(?=\/)/g);
    // 获取模块路径
    let modulePath = arrPath && arrPath.length ? arrPath[0] : '';
    const routers = router.getRoutes() || [];
    let tMoudle = {};
    // 根据路径获取模块
    if (modulePath) {
      tMoudle = routers.find(item => modulePath == item.path);
    }
    // 看当前路由是否在不统计列表内
    if (noStatisticsList.includes(to.path)) {
      options.sign = '1';// 标记，1（不统计）, 默认0(统计) 
    }
    // 必须要有名称
    if (options.dataType || to.meta?.title) {
      addRouterLogApi({
        "opType": options.opType, //类型
        "modules": options.moduleName || tMoudle.meta?.title || to.meta?.title,//模块
        "dataType": options.dataType || to.meta?.title,//名称
        "path": options.path || to.path || "",//路径
        "sign": options.sign, //是否统计
      }).then(res => {
        const { code, data } = res;
        if (code != 200) {
          console.log(data || ((options.path || to.path) + '：日志添加失败！'));
        }
      }).catch(err => {
        console.log(err);
      })
    }
  }
}